package com.jzo2o.foundations.task;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.IRegionServeService;
import com.jzo2o.foundations.service.IRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * @Author: liZhiJun
 * @CreateTime: 2025-09-24
 * @Description: 缓存任务
 * @Version: 1.0
 */
@Slf4j
@Component
public class CacheTask {

    @Autowired
    private IRegionServeService serveService;
    @Autowired
    private IRegionService regionService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 缓存任务
     *  每天0点执行更新缓存 首页服务列表、热门服务、服务类型
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cacheTask(){
        log.info("缓存任务开始执行");
        //1.查询所有启用的区域
        List<RegionSimpleResDTO> resgionList = regionService.queryActiveRegionListCache();
        deleteCache();
        if(CollectionUtils.isEmpty(resgionList)){
            log.info("没有启用的区域");
            return;
        }
        for (RegionSimpleResDTO region : resgionList) {
            //1.2 添加缓存
            regionService.queryActiveRegionListCache();
            serveService.hotServeList(region.getId());
            serveService.firstPageServeList(region.getId());
            serveService.serveTypeList(region.getId());
        }

    }

    public void deleteCache() {
        log.info("删除缓存地区");
        // 获取所有匹配的键并删除
        Set<String> hotServeKeys = redisTemplate.keys(RedisConstants.CacheName.HOT_SERVE + "*");
        Set<String> serveTypeKeys = redisTemplate.keys(RedisConstants.CacheName.SERVE_TYPE + "*");
        Set<String> serveIconKeys = redisTemplate.keys(RedisConstants.CacheName.SERVE_ICON + "*");
        redisTemplate.delete(RedisConstants.CacheName.JZ_CACHE+"::"+"ACTIVE_REGIONS");
        if (!hotServeKeys.isEmpty()) {
            redisTemplate.delete(hotServeKeys);
        }
        if (serveTypeKeys != null && !serveTypeKeys.isEmpty()) {
            redisTemplate.delete(serveTypeKeys);
        }
        if (serveIconKeys != null && !serveIconKeys.isEmpty()) {
            redisTemplate.delete(serveIconKeys);
        }

    }
}
